<?php
declare (strict_types=1);

namespace app\wxApi\controller;

use app\common\JwtAuth;
use DateInterval;
use think\Exception;
use think\facade\Cache;
use think\facade\Db;
use think\Request;
use think\Response;
use WeChat\Mini;

class Auth
{
    const TABLE_NAME='examinee_baseinfo';
    /**
     * 显示资源列表
     *
     * @return Response
     */
    public function index()
    {
        //
    }

    /**
     * 显示创建资源表单页.
     *
     * @return Response
     */
    public function create()
    {
        //
    }

    /**
     * 保存新建的资源
     *
     * @param \think\Request $request
     * @return Response
     */
    public function save(Request $request)
    {
        //
    }

    /**
     * 显示指定的资源
     *
     * @param int $id
     * @return Response
     */
    public function read($id)
    {
        //
    }

    /**
     * 显示编辑资源表单页.
     *
     * @param int $id
     * @return Response
     */
    public function edit($id)
    {
        //
    }

    /**
     * 保存更新的资源
     *
     * @param \think\Request $request
     * @param int $id
     * @return Response
     */
    public function update(Request $request, $id)
    {
        //
    }

    /**
     * 删除指定资源
     *
     * @param int $id
     * @return Response
     */
    public function delete($id)
    {
        //
    }

    /**
     * @return
     */
    public function login(Request $request): Response
    {
        try {
            $jsCode = $request->post('js_code');
            if (isset($jsCode) && !empty($jsCode)) {
                $response = Mini::login($jsCode);
                if (isset($response['errcode'])) {
                    throw new Exception($response['errmsg'], $response['errcode']);
                }
                $details = Db::name(self::TABLE_NAME)->where('openid', '=', $response['openid'])->find();
                if ($details == null) {
                    $insertData = [
                        'openid' => $response['openid'],
                        'create_time' => time(),
                        'session_key' => $response['session_key'],
                    ];
                    $id  =Db::name(self::TABLE_NAME)->insertGetId($insertData);
                    if(!$id){
                        throw new Exception('登录失败',9001);
                    }
                    $details =  Db::name(self::TABLE_NAME)->find($id);
                }
                $jwt = new JwtAuth();
               
                // 生成登录token并且写入缓存  暂定缓存 时间为1天
                $token = $jwt->createToken($details['id']);
                $update  =Db::name(self::TABLE_NAME)->where('id','=',$details['id'])->update(['token'=>$token]);
                if($update!==false){
                    Cache::set($token, $details, DateInterval::createFromDateString('1 day'));
                    $cache = Cache::get($token);
                    return success([...$details,'token'=>$token]);
                }else{
                    throw new Exception('登录失败',9002);
                }

            } else {
                throw new Exception('登录无效', 9004);
            }
            return success($request->post());
        } catch (\Exception $e) {
            return error([], $e->getCode() ?: 9006, $e->getMessage());
        }

    }
    public function examinerLogin(Request $request){
        try {
            $jsCode = $request->post('js_code');
            if (isset($jsCode) && !empty($jsCode)) {
                $response = Mini::login($jsCode);
                if (isset($response['errcode'])) {
                    throw new Exception($response['errmsg'], $response['errcode']);
                }
                  $details = Db::name('examiner_baseinfo')->alias('baseinfo')->leftJoin('examiner','examiner.id=baseinfo.examiner_id')->where('openid', '=', $response['openid'])->find();


                if ($details == null) {
                    $insertData = [
                        'openid' => $response['openid'],
                        'create_time' => time(),
                        'session_key' => $response['session_key'],
                    ];
                    $id  = Db::name('examiner_baseinfo')->insertGetId($insertData);
                    if(!$id){
                        throw new Exception('登录失败',9001);
                    }
                    $details =  Db::name('examiner_baseinfo')->find($id);
                }
                $jwt = new JwtAuth();
                //  print_r($details);
                // 生成登录token并且写入缓存  暂定缓存 时间为1天
                $token = $jwt->createToken('examiner_'.$details['id']);
                $update  =Db::name('examiner_baseinfo')->where('id','=',$details['id'])->update(['token'=>$token]);
                if($update!==false){
                    Cache::delete($token);
                    Cache::set($token, $details, DateInterval::createFromDateString('1 day'));
                    $cache = Cache::get($token);
                    return success([...$details,'token'=>$token]);
                }else{
                    throw new Exception('登录失败',9002);
                }

            } else {
                throw new Exception('登录无效', 9004);
            }
            return success($request->post());
        } catch (\Exception $e) {
            return error([], $e->getCode() ?: 9006, $e->getMessage());
        }
    }
}
